package com.solcoo.service;

import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.solcoo.controller.AbstractController;
import com.solcoo.controller.JsonResult;
import com.solcoo.dao.ZhangHuDao;
import com.solcoo.dao.ZheKouDao;
import com.solcoo.pojo.ZhangHu;
import com.solcoo.pojo.ZheKou;

@Service
public class ZheKouService extends AbstractController {

	@Resource
    private ZheKouDao zheKouDao;
	@Resource
    private ZhangHuDao zhangHuDao;

	public JsonResult throwExcepshAddDz(ZheKou zhekou) throws Exception {
		List<ZheKou> oldzks = zheKouDao.queryListByShid(zhekou.getShanghuid());
		if(oldzks!=null && oldzks.size()>0) {
			ZheKou last = oldzks.get(oldzks.size()-1);
			if(zhekou.getJingyanz() <= last.getJingyanz()) {
				return this.getFailJsonResult("经验值输入有误，请核对");
			}
			if(zhekou.getZhekoul() >= last.getZhekoul()) {
				return this.getFailJsonResult("折扣输入有误，请核对");
			}
		}
		zheKouDao.add(zhekou);
		List<ZheKou> zks = zheKouDao.queryListByShid(zhekou.getShanghuid());
		updateAllAccount(zhekou.getShanghuid());
		return this.getSuccessJsonResult(zks, 0);
	}

	// 计算该商户对应所有的账户等级
	private void updateAllAccount(int shanghuid) throws Exception {
		List<ZhangHu> zhs = zhangHuDao.queryListByShid(shanghuid);
		if(zhs!=null && zhs.size()>0) {
			List<ZheKou> zks = zheKouDao.queryListByShid(shanghuid);
			double jingyanz = 0;
			int dengji = 0;
			double zhekoul = 0;
			for(ZhangHu zh:zhs) {
				jingyanz = zh.getJingyanz();
				dengji = zh.getDengji();
				for(ZheKou zk:zks) {
					if(zk.getJingyanz()<=jingyanz && zk.getDengji()>dengji) {
						dengji = zk.getDengji();
						zhekoul = zk.getZhekoul();
					}
				}
				if(dengji > zh.getDengji()) {
					zh.setDengji(dengji);
					zh.setZhekoul(zhekoul);
					zhangHuDao.update(zh);
				}
			}
		}
	}
}
